package com.example.state.machine.config;

import com.example.state.machine.enums.OrderEvent;
import com.example.state.machine.enums.OrderState;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineModelConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.config.model.StateMachineModelFactory;
import org.springframework.statemachine.data.*;
import org.springframework.statemachine.data.jpa.JpaPersistingStateMachineInterceptor;
import org.springframework.statemachine.data.jpa.JpaStateMachineRepository;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.persist.StateMachineRuntimePersister;
import org.springframework.statemachine.service.DefaultStateMachineService;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.statemachine.state.State;

import java.math.BigDecimal;
import java.util.EnumSet;

/*
 * 订单状态机配置
 *
 */
@Configuration
@EnableStateMachineFactory  // 启用状态机工厂
public class OrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<OrderState, OrderEvent> {

    @Resource
    private StateRepository<? extends RepositoryState> stateRepository;

    @Resource
    private TransitionRepository<? extends RepositoryTransition> transitionRepository;

    /*
     * 配置状态机模型，参考 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#configuring-model
     */
    @Override
    public void configure(StateMachineModelConfigurer<OrderState, OrderEvent> model) throws Exception {
        model
                .withModel()
                .factory(modelFactory());
    }

    @Bean
    public RepositoryStateMachineModelFactory modelFactory() {
        return new RepositoryStateMachineModelFactory(stateRepository, transitionRepository);
    }
    // 以上参考 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#statemachine-examples-datajpa





    @Bean
    public StateMachineRuntimePersister<OrderState, OrderEvent, String> stateMachineRuntimePersister(
            JpaStateMachineRepository jpaStateMachineRepository) {
        return new JpaPersistingStateMachineInterceptor<>(jpaStateMachineRepository);
    }

    @Bean
    public StateMachineService<OrderState, OrderEvent> stateMachineService(
            StateMachineFactory<OrderState, OrderEvent> stateMachineFactory,
            StateMachineRuntimePersister<OrderState, OrderEvent, String> stateMachineRuntimePersister) {
        return new DefaultStateMachineService<>(stateMachineFactory, stateMachineRuntimePersister);
    }
    // 以上两个配置参考状态机 Data Persist 章节 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#statemachine-examples-datapersist



    @Resource
    private StateMachineRuntimePersister<OrderState, OrderEvent, String> stateMachineRuntimePersister;

    /*
     * 配置状态机通用设置
     */
    @Override
    public void configure(StateMachineConfigurationConfigurer<OrderState, OrderEvent> config) throws Exception {
        // 配置状态机参数，参考 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#statemachine-config-commonsettings
        config
                // 配置状态机启动、监听器等
                .withConfiguration()
                // 自动启动状态机
                .autoStartup(true)
                // 配置状态机监听器
                .listener(listener())
                .and()
                // 配置状态机持久化，参考 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#statemachine-examples-datapersist
                .withPersistence()
                .runtimePersister(stateMachineRuntimePersister);

    }

    /*
     * 定义可能的状态并选择初始和可选的结束状态。
     */
    @Override
    public void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {
        // 配置状态
        states
                .withStates()
                // 参考官网 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#configuring-pseudo-states
                .initial(OrderState.UNPAID, stateContext -> {
                    // 初始化时执行某项作
                    System.out.println("订单已创建等待支付，请在 15 分钟内完成支付。初始化订单状态为：" + OrderState.UNPAID);
                })    // 初始状态
                .end(OrderState.COMPLETED)     // 终态：已完成
                .end(OrderState.CANCELLED)     // 终态：已取消
                .states(EnumSet.allOf(OrderState.class));
    }

    /*
     * 定义状态之间的切换规则
     */
    @Override
    public void configure(StateMachineTransitionConfigurer<OrderState, OrderEvent> transitions) throws Exception {
        // 状态流转规则
        transitions
                // 支付事件：UNPAID → PAID（需校验金额）
                .withExternal()
                .source(OrderState.UNPAID).target(OrderState.PAID)
                .event(OrderEvent.PAY)
                // 决定是否允许状态转换的条件（如支付金额必须大于0）
                // 参考官网 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#configuring-guards
                .guard(context -> {
                    Order order = context.getMessage().getHeaders().get("order", Order.class);
                    if (order != null) {
                        return order.getAmount().compareTo(BigDecimal.ZERO) > 0;  // 守卫条件：金额必须大于0
                    }
                    return false;
                })
                // 动作，状态转换时执行的逻辑（如发送支付成功通知）
                // 此处的 context 就是 状态转换的上下文，包含状态、事件、目标状态等，其中获取消息中的内容要和 stateMachine.sendEvent 发送时设置的内容对应
                .action(context -> {
                    OrderEvent orderEvent = context.getEvent();
                    System.out.println(orderEvent);
                }, context -> {
                    // 获取异常信息
                    String message = context.getException().getMessage();
                    System.out.println("订单支付失败，原因：" + message);
                })
                .and()

                // 取消事件：UNPAID → CANCELLED
                .withExternal()
                .source(OrderState.UNPAID).target(OrderState.CANCELLED)
                .event(OrderEvent.CANCEL)
                .and()

                // 发货事件：PAID → SHIPPED
                .withExternal()
                .source(OrderState.PAID).target(OrderState.SHIPPED)
                .event(OrderEvent.SHIP)
                // 动作，状态转换时执行的逻辑（如发送支付成功通知、扣减库存等）
                // 参考官网 https://docs.spring.io/spring-statemachine/docs/4.0.0/reference/index.html#statemachine-config-actions
                .action(context -> {
                    // 此处的 context 就是 状态转换的上下文，包含状态、事件、目标状态等，其中获取消息中的内容要和 stateMachine.sendEvent 发送时设置的内容对应
                    Order order = context.getMessage().getHeaders().get("order", Order.class);
                    if (order != null) {
                        deductInventory(order);  // 扣减库存
                    }
                })
                .and()

                // 确认收货事件：SHIPPED → COMPLETED
                .withExternal()
                .source(OrderState.SHIPPED).target(OrderState.COMPLETED)
                .event(OrderEvent.CONFIRM);
    }

    // 状态监听器
    @Bean
    public StateMachineListener<OrderState, OrderEvent> listener() {
        return new StateMachineListenerAdapter<>() {
            @Override
            public void stateChanged(State<OrderState, OrderEvent> from, State<OrderState, OrderEvent> to) {
                System.out.println("状态更改为 " + to.getId());

            }
        };
    }

    // 错误处理
    @Bean
    public Action<OrderState, OrderEvent> errorAction() {
        return context -> {
            // RuntimeException("MyError") added to context
            String message = context.getException().getMessage();
            System.out.println("发生错误：" + message);
        };
    }

    // 模拟扣减库存
    private void deductInventory(Order order) {
        System.out.println("扣减库存成功，订单号：" + order.getOrderNumber());
    }
}